package com.hos.utils;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.io.ByteArrayInputStream;
import java.security.Security;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECPoint;

public class PKCS7Parser {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public static String getFacetID(String developmentCertificate) {
        try {
            // 去除PEM头尾标记和换行符
            String base64Key = developmentCertificate
                    .replace("-----END CERTIFICATE-----", "")
                    .replace("-----BEGIN CERTIFICATE-----", "")
                    .replaceAll("\\s+", "");
            byte[] encodedCert = Base64.decodeBase64(base64Key);
            // 获取04+X+Y格式的公钥
            byte[] rawECCPublicKey = parseRawECCPublicKey(encodedCert);
            // 进行Base64编码
            String faceIdTemp = Base64.encodeBase64String(rawECCPublicKey);
            // 去除Base64编码后末尾可能存在的等号
            return "ohos:app-id:" + removeTrailingEquals(faceIdTemp);
        } catch (Exception e) {
            return "获取异常:" + e.getMessage();
        }
    }

    /**
     * 去除字符串末尾的等号
     */
    public static String removeTrailingEquals(String input) {
        if (input == null || input.isEmpty()) {
            return input;
        }
        int end = input.length();
        while (end > 0 && input.charAt(end - 1) == '=') {
            end--;
        }
        return input.substring(0, end);
    }

    /**
     * 获取04+X+Y格式的公钥
     */
    public static byte[] parseRawECCPublicKey(byte[] rawCert) throws Exception {
        // 加载裸证书（无PEM头尾）
        CertificateFactory certFactory = CertificateFactory.getInstance("X.509", "BC");
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(rawCert));
        // 获取ECC公钥对象
        ECPublicKey ecPublicKey = (ECPublicKey) cert.getPublicKey();
        ECPoint ecPoint = ecPublicKey.getW();
        // 转换为未压缩格式(04 + X + Y)
        byte[] xBytes = ecPoint.getAffineX().toByteArray();
        byte[] yBytes = ecPoint.getAffineY().toByteArray();
        // 标准化长度（32字节）
        byte[] normalizedX = new byte[32];
        byte[] normalizedY = new byte[32];
        System.arraycopy(xBytes, Math.max(0, xBytes.length - 32), normalizedX, Math.max(0, 32 - xBytes.length), Math.min(32, xBytes.length));
        System.arraycopy(yBytes, Math.max(0, yBytes.length - 32), normalizedY, Math.max(0, 32 - yBytes.length), Math.min(32, yBytes.length));
        // 组合为04+X+Y格式
        byte[] uncompressedKey = new byte[65];
        uncompressedKey[0] = 0x04; // 未压缩标识
        System.arraycopy(normalizedX, 0, uncompressedKey, 1, 32);
        System.arraycopy(normalizedY, 0, uncompressedKey, 33, 32);
        return uncompressedKey;
    }
}
